package com.example.cabinetcontrol;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
import com.example.cabinetcontrol.data.Constant;
import com.example.cabinetcontrol.port.SerialPortService;
import com.example.cabinetcontrol.util.ILockCallBack;
import com.example.cabinetcontrol.util.PreferencesUtils;

/**
 * Created by Administrator on 2019/3/19 0019.
 */

public class CabinetClass implements ILockControl {

    private SerialPortService.mBinder binder;
    ILockCallBack iCabinetCallBack;

    Context context;
    Constant constant;

    public CabinetClass(Context context,ILockCallBack iCabinetCallBack) {
        this.context = context;
        this.iCabinetCallBack = iCabinetCallBack;

        Intent intent = new Intent(context, SerialPortService.class);
        // 传入服务的Intent，和已经定义好的ServiceConnection对象，BIND_AUTO_CREATE为标志，表示活动和服务绑定后自动创建一个服务的实例
        context.bindService(intent, connection, context.BIND_AUTO_CREATE);
    }

    //开启大门
    @Override
    public void openDoor() {
        binder.openDoor();
    }

    //获取门状态
    @Override
    public void getDoorStatus() {
        binder.getDoorStatus();
    }

    //获取柜机标签数据
    @Override
    public void getTemperature() {
        binder.getTemperature();
    }

    //设置落锁等待时间
    @Override
    public boolean setLockDelay(int time) {
        try {
            if (time>0) {
                PreferencesUtils.putInt(context, constant.LOCK_OUTTIME, time);
                return true;
            }
            else {
                return false;
            }
        }
        catch (Exception e){
            return false;
        }
    }

    //关闭服务
    @Override
    public void stop() {
        binder.stop();
        stopService();
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        // 活动和服务的绑定失去的时候自动调用，比如服务被杀死或者报错，这时候ServiceConnection会保持激活，在活动下次启动时会收到一个通知
        public void onServiceDisconnected(ComponentName name) {
            Log.d("Context", "onServiceDisonnected executed");
            binder = null;
        }

        @Override
        // 活动和服务解绑的时候自动调用，即bindService()函数调用时
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (SerialPortService.mBinder) service; // 通过Service向下转型得到一个MyService.mBinder的对象
            binder.setICabinetCallBack(iCabinetCallBack);
            Log.d("Context", "onServiceConnected executed");
        }
    };


    public void stopService(){
        context.unbindService(connection);
    }

}
